package com.android.li.temperature.service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.android.li.temperature.R;
import com.android.li.temperature.util.AlertWakeLock;
import com.android.li.temperature.util.Constant;

public class PhoneStatusService extends Service {

    public static final String ACTION_START_MONITOR = "action_start_monitor";
    public static final String ACTION_STOP_MONITOR = "action_stop_monitor";

    public static final int NOTICE_ID = 0x88;


    private PhoneStatusManager mPhoneStatusManager;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(Constant.TAG, "PhoneStatusService create");
        mPhoneStatusManager = PhoneStatusManager.getInstance(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(Constant.TAG, "PhoneStatusService destory");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (null == intent) {
            return super.onStartCommand(intent, flags, startId);
        }

        String action = intent.getAction();
        if (ACTION_START_MONITOR.equals(action)) {
            Log.d(Constant.TAG, ACTION_START_MONITOR);

            AlertWakeLock.acquireCpuWakeLock(this);

            startForground();

            if (null != mPhoneStatusManager) {
                mPhoneStatusManager.startDataSource();
            }

        } else if (ACTION_STOP_MONITOR.equals(action)) {
            Log.d(Constant.TAG, ACTION_STOP_MONITOR);

            stopForground();

            if (null != mPhoneStatusManager) {
                mPhoneStatusManager.stopDataSource();
            }

            AlertWakeLock.releaseCpuLock();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 保活，防止被系统 kill
     * 
     * 提高服务进程优先级为前台进程(adj值)
     */
    private void startForground() {
        Log.d(Constant.TAG, "startForground");

        Notification.Builder nb = new Notification.Builder(this);
        nb.setWhen(System.currentTimeMillis());
        nb.setSmallIcon(R.drawable.ic_launcher);
        nb.setContentTitle(getString(R.string.app_name));
        nb.setContentText(getString(R.string.notification_content));
        nb.setPriority(Notification.PRIORITY_HIGH);
        startForeground(NOTICE_ID, nb.build());
    }

    /**
     * 取消进程优先级(adj值)
     */
    private void stopForground() {
        Log.d(Constant.TAG, "stopForground");

        stopForeground(true);
    }

}
